package com.cycrix.tcp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import android.os.Handler;
import android.os.Message;


public class TcpServer implements Runnable {
 
    public static final int DID_ACCEPT = 0;
    public static final int DID_ERROR = 1;
    
    private Handler handler;
    private ServerSocket ss;
 
    public TcpServer(int port) throws IOException {
        this(port, new Handler());
    }
 
    public TcpServer(int port, Handler _handler) throws IOException {
        handler = _handler;
        ss = new ServerSocket(port);
        Thread thread = new Thread(this);
        thread.start();
    }
    
    public void close() throws IOException {
    	ss.close();
    }
 
    public void run() {
    	//handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
    	try {
			
			while(true) {
				Socket s = ss.accept();
				handler.sendMessage(Message.obtain(handler, TcpServer.DID_ACCEPT, s));
			}
			
		} catch (IOException e) {
			if (!e.getMessage().equalsIgnoreCase("Socket closed")) {
				handler.sendMessage(Message.obtain(handler, TcpServer.DID_ERROR));
			}
		}
    }
}